<template>
    <view class="discover-page">
        <!-- 头部组件 -->
        <view class="fixed-header">
            <Header :header-data="headerData" />
        </view>
        <view class="dynamic-info">
            <view class="dynamic-header" @click="navigateToReleaseDy">

                <uni-icons type="plus-filled" size="18"></uni-icons>
                <text>发布</text>
            </view>

            <!-- 动态列表 -->
            <view class="dynamic-item" v-for="(item, index) in dynamicList" :key="index" :data-post-id="item.post_id">
                <!-- 动态内容 -->
                <view class="dynamic-content">
                    <image class="avatar" :src="item.avatar" mode="aspectFill" @click="openUserProfile(item.user_id)">
                    </image>
                    <view class="text-wrap">
                        <view class="header">
                            <view>
                                <view class="nickname">{{ item.nickname }}</view>
                                <view class="time">{{ formatTime(item.post_time) }}</view>
                            </view>
                            <uni-icons type="more-filled" size="26" color="#A3A6B7" style="margin-top: -30rpx;"
                                @tap="showMoreOptions(item, index)"></uni-icons>
                        </view>

                        <view class="content-container" :class="{ 'expanded': item.isExpanded }">
                            <view class="content" :ref="'content_' + index" :id="'content_' + index">{{ item.content }}
                            </view>
                            <text v-if="item.shouldShowToggle" class="toggle-btn"
                                @tap.stop="toggleContentExpand(item, index)">
                                {{ item.isExpanded ? '收起' : '...展开' }}
                            </text>
                        </view>
                        <!-- 添加动态媒体 -->
                        <view class="dynamic-images" v-if="item.media && item.media.length > 0">
                            <template v-for="(media, mediaIndex) in item.media.slice(0, 9)">
                                <image v-if="media.type === 'image'" :src="media.url" mode="aspectFill"
                                    class="dynamic-img" :class="{ 'single-img': item.media.length === 1 }"
                                    :key="mediaIndex" @click="openImageViewer(item, mediaIndex)"></image>
                                <!-- :poster="getVideoPoster(media)" -->
                                <view v-else-if="media.type === 'video'" class="video-container"
                                    :class="{ 'single-img': item.media.length === 1 }"
                                    :key="'media-' + mediaIndex + '-' + media.type">
                                    <video :src="media.url" mode="aspectFill" class="dynamic-video"
                                        :ref="'video-' + index + '-' + mediaIndex"
                                        :id="'video-' + index + '-' + mediaIndex" :controls="false"
                                        :show-center-play-btn="false" :show-fullscreen-btn="false"
                                        :show-play-btn="false" :show-progress="false" :show-mute-btn="false"
                                        :enable-progress-gesture="false" :enable-progress-tap="false"
                                        :enable-play-gesture="false" :show-loading="false"
                                        @loadedmetadata="updateVideoDuration($event, item, index, mediaIndex)"
                                        @click.stop="handleVideoClick($event, item, index, mediaIndex)"></video>
                                    <!-- 播放按钮覆盖层 -->
                                    <image class="video-play-btn" :src="getFullImageUrl('@/static/faxian/bofan.png')"
                                        @click.stop="handleVideoClick($event, item, index, mediaIndex)"
                                        style="width:60rpx;height: 76rpx;"></image>
                                    <!-- 左下角时长显示 -->
                                    <view class="video-duration" v-if="media.duration">
                                        {{ formatVideoDuration(media.duration) }}
                                    </view>
                                </view>
                            </template>
                        </view>
                        <view class="info">
                            <button open-type="share" class="info-item">
                                <image class="menu-icon" :src="getFullImageUrl('@/static/faxian/share.png')"></image>

                                <text>分享</text>
                            </button>
                            <view @tap="openCommentModal(item, index)" class="info-item">
                                <image class="menu-icon" :src="getFullImageUrl('@/static/faxian/comment.png')"></image>
                                <text>
                                    {{ item.comment_count > 0 ? item.comment_count : '评论' }}
                                </text>
                            </view>
                            <view @tap="toggleLike(item)" class="info-item" :disabled="item.isLikedDisabled">
                                <!-- <uni-icons :type="item.liked ? 'heart-filled' : 'heart'" size="20"
                                    :color="item.liked ? '#F76F17' : '#A3A6B7'"></uni-icons> -->
                                <image class="menu-icon" :src="getFullImageUrl('@/static/faxian/like.png')"
                                    v-show="!item.liked" style="width: 33rpx;"></image>

                                <image class="menu-icon" :src="getFullImageUrl('@/static/faxian/likeflill.png')"
                                    v-show="item.liked" style="width: 33rpx;"></image>

                                <text :style="{ color: item.liked ? '#F76F17' : '#A3A6B7' }">
                                    {{ item.likes > 0 ? item.likes : '点赞' }}
                                </text>
                            </view>
                        </view>
                    </view>
                </view>
                <view style="width: 580rpx; height: 1rpx; background-color: #EEF2F3; margin-left: calc(50% - 250rpx);">
                </view>

                <!-- 评论弹窗（Unipop 底部弹窗） -->
                <uni-popup :ref="'commentPopup' + index" type="bottom" @close="closePopup('commentPopup', index)">
                    <view class="comment-popup">
                        <view class="popup-title">全部评论 {{ item.comment_count }}</view>
                        <!-- 评论列表 -->
                        <scroll-view class="comment-list" scroll-y="true"
                            @scrolltolower="loadMoreComments($event, index)"
                            v-if="item.comments && item.comments.length > 0">
                            <view class="comment-item" v-for="(comment, cIndex) in item.comments" :key="cIndex">
                                <view class="comment-header">
                                    <!-- 添加用户头像 -->
                                    <image class="comment-avatar" mode="aspectFill"
                                        :src="comment.avatar || '/static/image/logo.jpg'">
                                    </image>
                                    <view class="comment-content">
                                        <view class="comment-header-left">
                                            <text class="comment-nickname">{{ comment.nickname }}</text>
                                            <text class="comment-time">{{ comment.time }}</text>
                                        </view>
                                        <!-- 点赞功能 -->
                                        <view class="comment-actions" @tap="likeComment(comment, cIndex, item.id)">
                                            <text class="comment-likesNum" :class="{ 'liked': comment.liked }">
                                                {{ comment.likes > 0 ? comment.likes : '点赞' }}
                                            </text>
                                            <uni-icons :type="comment.liked ? 'heart-filled' : 'heart'" size="20"
                                                :color="comment.liked ? '#F76F17' : '#A3A6B7'">
                                            </uni-icons>
                                        </view>
                                    </view>
                                </view>
                                <view class="comment-text">
                                    <text @tap="replyComment(comment, cIndex, index)">{{ comment.content }}</text>
                                </view>

                                <!-- 回复列表 -->

                                <view class="reply-list" v-if="comment.replies && comment.replies.length > 0">
                                    <view class="reply-item" v-for="(reply, rIndex) in getVisibleReplies(comment)"
                                        :key="rIndex">
                                        <text class="reply-content" @tap="replyComment(reply, rIndex, cIndex)">{{
                                            reply.content }}</text>
                                    </view>

                                    <view class="view-more" v-if="comment.replies.length > 2"
                                        @tap="viewAllReplies(comment)">
                                        {{ comment.isExpanded ? '收起全部' : '查看全部' }} {{ comment.reply_count }} 条回复
                                    </view>
                                </view>
                            </view>
                        </scroll-view>
                        <view class="no-comment" v-else>
                            <image class="menu-icon" :src="getFullImageUrl('@/static/faxian/nocom.png')"></image>
                            <!-- <text>当前暂无评论</text> -->
                        </view>

                        <!-- 评论输入 -->
                        <view class="comment-input-wrap">
                            <input class="comment-input" v-model="commentValue"
                                :placeholder="replyTo ? '回复 @' + replyTo : '输入评论内容'" />
                            <button class="send-btn" :class="{ active: commentValue.trim() }"
                                @tap="sendComment(item, replyTo, replyCommentIndex, replyDynamicIndex)">发送</button>
                        </view>
                    </view>
                </uni-popup>


                <uni-popup ref="bgPopup" type="bottom">
                    <view class="custom-popup">

                        <view class="popup-btn" @click="openReportModal(currentItem, currentItemIndex)">举报</view>
                        <view class="popup-cancel" @click="closeBgPopup">取消</view>
                    </view>
                </uni-popup>
                <!-- 举报弹窗 -->
                <uni-popup :ref="'reportPopup' + index" type="center" @close="closePopup('reportPopup', index)">
                    <view class="report-popup">
                        <view class="report-popup-header">
                            <text class="popup-title">举报说明<text style="color: #F76F17;">*</text></text>
                            <text class="cancel" @click="closePopup('reportPopup', index)">取消返回</text>
                        </view>
                        <textarea class="report-textarea" v-model="reportReason" placeholder="输入您举报的原因"></textarea>
                        <button class="report-btn" :style="{ backgroundColor: reportReason ? '#BEFF33' : '#D0D4D7' }"
                            :disabled="!reportReason" @tap="submitReport(item, index)">确认提交</button>
                    </view>
                </uni-popup>
            </view>
        </view>
        <ImageViewer v-show="showImageViewer" :showViewer.sync="showImageViewer" :avatar="viewerData.avatar"
            :nickname="viewerData.nickname" :imageUrl="viewerData.imageUrl" :content="viewerData.content"
            :likeCount="viewerData.likeCount" :commentCount="viewerData.commentCount" :liked="viewerData.liked"
            @like="handleImageLike" @comment="handleImageComment" />

        <!-- 视频查看器 -->

        <videView :videoUrl="currentVideoUrl" v-show="showVideoView" :showViewer.sync="showVideoView"
            @videoClosed="onVideoClosed" />

        <!-- 发布成功弹窗 -->
        <view class="release-success-popup" v-if="showReleaseSuccessPopup">
            <view class="success-text">动态发布成功</view>
        </view>

    </view>
</template>

<script>
// 导入组件
import Header from '@/components/common/Header.vue';

import { request, initBaseUrl, getFullImageUrl } from '../../utils/request';

export default {
    components: {
        Header,
    },
    data() {
        return {
            dynamicList: [],
            commentValue: '',
            reportReason: '',
            currentItem: null,
            currentItemIndex: -1,
            replyTo: '',
            replyCommentIndex: -1,
            replyDynamicIndex: -1,
            replySubCommentIndex: -1, // 子评论索引，-1 表示不是回复子评论
            showImageViewer: false,
            viewerData: {
                avatar: '',
                nickname: '',
                imageUrl: '',
                content: '',
                likeCount: 0,
                commentCount: 0,
                liked: false
            },
            isCommentSending: false,
            currentVideoUrl: '', // 当前播放的视频URL
            showVideoView: false,
            userInfo: {
                nickname: '',
                avatar: ''
            },
            showReleaseSuccessPopup: false, // 控制发布成功弹窗的显示
            currentShareItem: null, // 当前要分享的动态项
            needCheckContentLength: false // 添加标志位，控制是否需要检查内容长度
        }
    },
    watch: {
        showVideoView: function (newVal) {
            if (newVal) {
                // 再次暂停所有视频，确保在新页面显示前完全暂停
                this.pauseAllVideos();
            }
        }
    },
    methods: {
        // 获取视频封面，优先使用阿里云封面
        getVideoPoster(media) {
            // 检查是否已经切换到本地封面
            if (media.useLocalPoster) {
                return this.getLocalVideoPoster(media);
            }
            // 否则使用阿里云封面
            return `${media.url}?x-oss-process=video/snapshot,t_0,f_jpg`;
        },

        // 更新视频时长
        updateVideoDuration(event, item, index, mediaIndex) {
            const duration = event.detail.duration;
            if (item.media && item.media[mediaIndex]) {
                this.$set(item.media[mediaIndex], 'duration', duration);
            }
        },

        // 格式化视频时长为 MM:SS 格式
        formatVideoDuration(seconds) {
            if (isNaN(seconds) || seconds === 0) {
                return '00:00';
            }
            const minutes = Math.floor(seconds / 60);
            const secs = Math.floor(seconds % 60);
            return (
                (minutes < 10 ? '0' + minutes : minutes) +
                ':' +
                (secs < 10 ? '0' + secs : secs)
            );
        },

        // 获取本地服务器的视频封面
        getLocalVideoPoster(media) {
            // 假设本地封面的URL格式是基于视频ID构建的
            // 你需要根据实际项目的URL规则进行调整
            return `/api/videos/${media.id}/cover.jpg`;
        },

        // 处理封面加载失败的情况
        handlePosterError(media) {
            // 标记使用本地封面
            media.useLocalPoster = true;
        },
        getFullImageUrl,
        // 暂停当前页面所有视频
        pauseAllVideos() {
            try {
                // 在微信小程序环境中，只使用uni-app提供的API来暂停视频
                // 遍历所有视频，通过视频上下文暂停
                for (let i = 0; i < this.dynamicList.length; i++) {
                    const item = this.dynamicList[i];
                    if (item.media && Array.isArray(item.media)) {
                        for (let j = 0; j < item.media.length; j++) {
                            const media = item.media[j];
                            if (media.type === 'video') {
                                const videoId = `video-${i}-${j}`;
                                const videoContext = uni.createVideoContext(videoId, this);
                                if (videoContext && videoContext.pause) {
                                    videoContext.pause();
                                }
                            }
                        }
                    }
                }

                // 额外尝试通过refs暂停视频
                if (this.$refs) {
                    for (const key in this.$refs) {
                        if (key.startsWith('video-')) {
                            const videoRef = this.$refs[key];
                            if (videoRef && videoRef.pause) {
                                videoRef.pause();
                            }
                        }
                    }
                }
            } catch (error) {
                console.error('暂停视频失败:', error);
            }
        },

        // 处理视频元素的点击事件，确保事件不冒泡
        handleVideoClick(event, item, index, mediaIndex) {
            // 阻止事件冒泡，避免触发其他点击事件
            event.stopPropagation();
            event.preventDefault();

            // 先暂停所有视频
            this.pauseAllVideos();

            // 设置当前要播放的视频URL并显示视频查看器
            this.currentVideoUrl = item.media[mediaIndex].url;

            // 使用setTimeout确保暂停操作完成后再显示视频查看器
            setTimeout(() => {
                this.showVideoView = true;
            }, 300);
        },

        // 监听视频查看器关闭事件，恢复页面状态
        onVideoClosed() {
            console.log('视频查看器已关闭');
            // 可以在这里添加一些清理操作
        },

        openVideoViewer(item, index, mediaIndex) {
            console.log("videoUrl456465456", item);

            // 先暂停所有视频
            this.pauseAllVideos();

            this.currentVideoUrl = item.media[mediaIndex].url;

            // 使用setTimeout确保暂停操作完成后再显示视频查看器
            setTimeout(() => {
                this.showVideoView = true;
            }, 300);
        },

        // 关闭视频查看器
        closeVideoPopup() {
            this.showVideoView = false;
        },
        // 格式化时间为 MM-DD HH:mm 格式
        formatTime(timeStr) {
            if (!timeStr) return '';
            const date = new Date(timeStr);
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            return `${month}-${day} ${hours}:${minutes}`;
        },
        openUserProfile(userId) {
            uni.navigateTo({
                url: `/pages/discover/myDynamics/myDynamics?user_id=${userId}`
            });
        },

        navigateToReleaseDy() {
            uni.navigateTo({
                url: '/pages/discover/releaseDy/releaseDy'
            });
        },

        // 显示更多选项菜单
        showMoreOptions(item, index) {
            // 存储当前项用于弹窗操作
            this.currentItem = item;
            this.currentItemIndex = index;
            // 直接打开举报选择弹窗
            this.$nextTick(() => {
                // 修复引用方式，确保正确访问bgPopup组件
                if (this.$refs.bgPopup && this.$refs.bgPopup.open) {
                    this.$refs.bgPopup.open();
                } else if (this.$refs.bgPopup && Array.isArray(this.$refs.bgPopup) && this.$refs.bgPopup[0] && this.$refs.bgPopup[0].open) {
                    this.$refs.bgPopup[0].open();
                }
            });
        },

        // 关闭举报选择弹窗
        closeBgPopup() {
            if (this.$refs.bgPopup && this.$refs.bgPopup.close) {
                this.$refs.bgPopup.close();
            } else if (this.$refs.bgPopup && Array.isArray(this.$refs.bgPopup) && this.$refs.bgPopup[0] && this.$refs.bgPopup[0].close) {
                this.$refs.bgPopup[0].close();
            }
        },
        // 打开举报弹窗
        openReportModal(item, index) {
            this.currentItem = item;
            this.$nextTick(() => {
                this.$refs[`reportPopup${index}`][0].open();
            });
        },
        // 提交举报
        submitReport(item, index) {
            if (!this.reportReason.trim()) return

            // 显示加载提示
            uni.showLoading({
                title: '提交中...',
                mask: true
            })

            // 调用后端接口
            request({
                url: 'discover/report/submit',
                method: 'POST',
                data: {
                    post_id: item.post_id,
                    report_reason: this.reportReason
                }
            }).then(res => {
                uni.hideLoading()
                if (res.code === 200) {
                    uni.showToast({
                        title: '举报提交成功，等待审核',
                        icon: 'success',
                        duration: 2000
                    })
                } else {
                    uni.showToast({
                        title: res.msg || '举报提交失败',
                        icon: 'none',
                        duration: 2000
                    })
                }
                // 不管成功失败都关闭弹窗
                this.closePopup('reportPopup', index)

                this.closeBgPopup()
                // 举报后清空输入框
                this.reportReason = ''
            }).catch(err => {
                uni.hideLoading()
                uni.showToast({
                    title: '网络错误，请稍后重试',
                    icon: 'none',
                    duration: 2000
                })
                console.error('提交举报失败:', err)
                // 网络错误也关闭弹窗
                this.closePopup('reportPopup', index)
                // 清空输入框
                this.reportReason = ''
            })
        },
        // 打开评论弹窗
        // 修改openCommentModal方法
        openCommentModal(item, index) {
            console.log('打开评论弹窗', item, index);
            this.currentItem = item;
            this.commentValue = '';
            this.replyTo = '';
            this.replyCommentIndex = -1;
            this.replySubCommentIndex = -1;
            this.replyDynamicIndex = -1;
            this.$nextTick(() => {
                console.log('即将打开弹窗', index);
                this.$refs[`commentPopup${index}`][0].open();
                console.log('弹窗已打开', index);
            });
            // 获取评论列表
            this.getComments(item.post_id, index, 1);

            // 如果有更多评论，继续加载
            const loadAllComments = () => {
                if (item.pagination && item.pagination.current_page < item.pagination.last_page) {
                    const nextPage = item.pagination.current_page + 1;
                    this.getComments(item.post_id, index, nextPage).then(() => {
                        loadAllComments();
                    });
                }
            };
            loadAllComments();
        },

        // 关闭弹窗通用方法
        closePopup(refName, index) {
            console.log('关闭弹窗', refName, index);
            if (refName === 'commentPopup') {
                console.log('即将关闭评论弹窗', index);
                this.$refs[`commentPopup${index}`][0].close();
                console.log('评论弹窗已关闭', index);
                this.commentValue = '';
                this.replyTo = '';
                this.replyCommentIndex = -1;
                this.replySubCommentIndex = -1;
                this.replyDynamicIndex = -1;
            } else if (refName === 'reportPopup') {
                this.$refs[`reportPopup${index}`][0].close();
                this.reportReason = '';
            }
        },
        // 新增方法
        getVisibleReplies(comment) {
            if (!comment || !comment.replies) return [];
            const showAll = comment.isExpanded || false;
            return showAll ? comment.replies : comment.replies.slice(0, 2);
        },

        // 关闭发布成功弹窗
        closeReleaseSuccessPopup() {
            this.showReleaseSuccessPopup = false;
        },
        // 回复评论
        // 修改replyComment方法
        replyComment(comment, cIndex, dIndex) {
            console.log("回复评论", comment, cIndex, dIndex)
            // 添加调试日志，检查comment对象是否包含user_id字段
            console.log('comment对象详细信息:', JSON.parse(JSON.stringify(comment)));
            // 设置回复对象
            this.replyTo = comment.reply_nickname ? comment.reply_nickname : comment.nickname;
            // 区分是主评论还是子评论
            if (comment.comment_id) {
                // 主评论
                this.replyCommentIndex = cIndex;
                this.replySubCommentIndex = -1; // 重置子评论索引
            } else if (comment.reply_id) {
                // 子评论
                this.replyCommentIndex = dIndex; // 存储主评论索引
                this.replySubCommentIndex = cIndex; // 存储子评论索引
            }

            this.replyDynamicIndex = dIndex;

            // 清空评论输入框的值
            this.commentValue = '';

            // 确保在弹窗完全渲染后执行滚动
            this.$nextTick(() => {
                // 滚动到评论输入框（小程序兼容版本）
                const query = uni.createSelectorQuery().in(this);
                query.select('.comment-input').boundingClientRect();
                query.selectViewport().scrollOffset();
                query.exec((res) => {
                    if (res && res[0] && res[1]) {
                        const inputTop = res[0].top;
                        const scrollTop = res[1].scrollTop;
                        uni.pageScrollTo({
                            scrollTop: scrollTop + inputTop - 100,
                            duration: 300
                        });
                    }
                });
            });
        },
        // 查看全部回复
        // 修改viewAllReplies方法
        // 修改sendComment方法


        // 修改viewAllReplies方法
        viewAllReplies(comment) {
            if (!comment) return;
            this.$set(comment, 'isExpanded', !comment.isExpanded);

            // 如果展开且有更多回复未加载
            if (comment.isExpanded && comment.reply_count > comment.replies.length) {
                this.loadMoreReplies(comment);
            }
        },

        // 发送评论
        async sendComment(item, replyTo, cIndex, dIndex) {
            console.log("发送评论", item)
            if (!this.commentValue.trim()) return;
            if (this.isCommentSending) return;

            this.isCommentSending = true;
            // 保存当前评论索引用于后续调用loadMoreReplies
            const currentCommentIndex = this.replyCommentIndex;

            try {
                let apiUrl = 'discover/Comment/create';
                let postData = {
                    post_id: item.post_id,
                    content: this.commentValue.trim()
                };

                // 如果是回复评论
                if (this.replyDynamicIndex !== -1) {
                    let comment;
                    console.log("回复评论索引", this.replyCommentIndex, this.replySubCommentIndex)
                    // 区分是回复主评论还是子评论
                    if (this.replySubCommentIndex === -1) {
                        // 回复主评论
                        comment = item.comments[this.replyCommentIndex];
                    } else {
                        // 回复子评论
                        comment = item.comments[this.replyCommentIndex].replies[this.replySubCommentIndex];
                    }
                    console.log("回复评论发送", comment)
                    apiUrl = 'discover/Comment/reply';

                    // 提取用户实际输入的内容（去掉"@用户名 "部分）
                    const userContent = this.commentValue.replace(`@${this.replyTo}`, '').trim();

                    // 格式化内容
                    const formattedContent = `${userContent}`;

                    // 确定父评论ID和被回复用户ID
                    // 如果是回复一条回复，需要使用回复的parent_comment_id作为父评论ID
                    // 被回复用户ID应该是回复的reply_user_id
                    let parentCommentId, beRepliedUserId;

                    console.log('回复评论对象:', comment);

                    if (comment.reply_id) {
                        // 回复子评论
                        parentCommentId = comment.parent_comment_id;
                        beRepliedUserId = comment.reply_user_id || comment.be_replied_user_id;
                        console.log('回复子评论:', { parentCommentId, beRepliedUserId, reply_user_id: comment.reply_user_id, be_replied_user_id: comment.be_replied_user_id });
                    } else {
                        // 回复主评论
                        parentCommentId = comment.comment_id;
                        // 添加详细的调试日志
                        console.log('回复主评论详细信息:', {
                            comment: JSON.parse(JSON.stringify(comment)),
                            user_id_source: comment.user_id,
                            be_replied_user_id_source: comment.be_replied_user_id,
                            user_id_type: typeof comment.user_id,
                            be_replied_user_id_type: typeof comment.be_replied_user_id
                        });
                        // 确保能正确获取被回复用户的ID
                        // 临时修复：如果comment.user_id不存在，尝试从其他字段获取或使用默认值
                        if (!comment.user_id) {
                            console.warn('comment.user_id is missing, attempting to use a default value or derive from other fields');
                            // 尝试从userInfo中获取当前登录用户的ID
                            if (this.userInfo && this.userInfo.id) {
                                comment.user_id = this.userInfo.id;
                            } else {
                                // 如果无法获取当前用户ID，使用一个默认的管理员ID
                                // 注意：这只是一个临时修复，实际应用中应该确保能正确获取用户ID
                                comment.user_id = 1; // 假设管理员ID为1
                            }
                        }
                        beRepliedUserId = comment.user_id || comment.be_replied_user_id;
                        console.log('回复主评论:', { parentCommentId, beRepliedUserId, user_id: comment.user_id, be_replied_user_id: comment.be_replied_user_id });
                    }

                    console.log('构建postData参数:', {
                        parentCommentId,
                        beRepliedUserId,
                        formattedContent
                    });

                    // 添加参数验证
                    if (!parentCommentId || !beRepliedUserId || !formattedContent) {
                        console.error('参数不能为空:', {
                            parentCommentId,
                            beRepliedUserId,
                            formattedContent
                        });
                        uni.showToast({ title: '参数不能为空', icon: 'none' });
                        this.isCommentSending = false;
                        return;
                    }

                    postData = {
                        parent_comment_id: parentCommentId,
                        be_replied_user_id: beRepliedUserId,
                        content: formattedContent
                    };

                    console.log('最终发送的postData:', postData);
                }

                console.log("发送评论参数", postData);
                console.log("发送评论URL", apiUrl);
                const res = await request({
                    url: apiUrl,
                    method: 'POST',
                    data: postData
                });
                console.log("发送评论响应", res);

                // 确保res对象存在且有code属性
                if (res && res.code === 1) {
                    uni.showToast({ title: '发送成功' });

                    // 立即在前端显示新评论
                    const newComment = {
                        reply_id: res.data.reply_id, // 确保有reply_id字段
                        comment_id: this.replyDynamicIndex !== -1 ? res.data.reply_id : res.data.comment_id,
                        content: this.replyDynamicIndex !== -1 ? `${this.userInfo.nickname || '匿名用户'} ${this.commentValue.trim()}` : this.commentValue.trim(),
                        nickname: this.userInfo.nickname || '匿名用户',
                        avatar: this.userInfo.avatar || '/static/image/logo.jpg',
                        time: new Date().toLocaleString(),
                        likes: 0,
                        liked: false,
                        replies: [],
                        reply_count: 0,
                        parent_comment_id: this.replySubCommentIndex !== -1 ? item.comments[this.replyCommentIndex].parent_comment_id : null // 设置父评论ID
                    };

                    // 如果是回复评论
                    if (this.replyDynamicIndex !== -1) {
                        // 回复主评论或子评论
                        const parentComment = item.comments[this.replyCommentIndex];
                        if (parentComment) {
                            // 不再直接添加到replies数组，而是依赖loadMoreReplies来更新
                            this.$set(parentComment, 'reply_count', parentComment.reply_count + 1);
                            // 更新评论总数，及时显示+1
                            this.$set(item, 'comment_count', item.comment_count + 1);
                            console.log('更新评论总数，及时显示+1:', {
                                oldCount: item.comment_count - 1,
                                newCount: item.comment_count,
                                postId: item.post_id
                            });

                            // 立即调用loadMoreReplies确保新回复显示
                            this.loadMoreReplies(parentComment);
                        }
                    } else {
                        // 添加新评论到评论列表顶部
                        if (!item.comments) {
                            this.$set(item, 'comments', []);
                        }
                        item.comments.unshift(newComment);

                        // 更新评论总数，及时显示+1
                        this.$set(item, 'comment_count', item.comment_count + 1);
                        console.log('更新评论总数，及时显示+1:', {
                            oldCount: item.comment_count - 1,
                            newCount: item.comment_count,
                            postId: item.post_id
                        });
                    }

                    // 关键修改：等待getComments完成
                    await this.getComments(item.post_id, dIndex, 1);

                    // 如果是回复评论，确保加载所有回复
                    if (currentCommentIndex !== -1) {
                        this.$nextTick(() => {
                            const comment = this.dynamicList[dIndex].comments[currentCommentIndex];
                            if (comment) {
                                this.loadMoreReplies(comment);
                            }
                        });
                    }

                    // 强制刷新视图
                    this.$forceUpdate();
                } else {
                    // 请求失败回滚乐观更新
                    if (this.replyCommentIndex !== -1) {
                        // 获取父评论
                        const parentComment = item.comments[this.replyCommentIndex];
                        if (parentComment && parentComment.replies) {
                            parentComment.replies.shift();
                        }
                    } else {
                        this.dynamicList[dIndex].comments.shift();
                    }
                    // 优先使用res.msg，如果不存在则使用res.data.msg
                    console.log("发送评论失败", res.msg)

                    // 确保能正确处理后端返回的错误信息
                    const errorMsg = res.msg || (res.data && res.data.msg) || '发布失败';
                    uni.showToast({ title: errorMsg, icon: 'none' });
                }
            } catch (error) {
                // 捕获异常时res可能未定义，直接使用默认提示
                console.error('发送评论异常:', error);
                uni.showToast({ title: '发送失败', icon: 'none' });
            } finally {
                // 重置状态
                this.commentValue = '';
                this.replyTo = '';
                this.replyCommentIndex = -1;
                this.replyDynamicIndex = -1;
                this.isCommentSending = false;
            }
        },

        // 获取用户信息
        async fetchUserInfo() {
            try {
                const res = await request({
                    url: 'User/info',
                    method: 'GET'
                });

                if (res.code === 200 && res.data) {
                    // 更新用户信息
                    this.userInfo = {
                        ...this.userInfo,
                        ...res.data,
                        // 确保头像路径正确
                        avatar: res.data.avatar || "/static/image/logo.jpg"
                    };
                    console.log("获取用户信息成功:", this.userInfo);
                } else {
                    uni.showToast({
                        title: res.msg || '获取用户信息失败',
                        icon: 'none'
                    });
                }
            } catch (error) {
                console.error('获取用户信息失败:', error);
                uni.showToast({
                    title: '网络错误',
                    icon: 'none'
                });
            }
        },
        // 新增loadMoreReplies方法
        async loadMoreReplies(comment) {
            try {
                const res = await request({
                    url: `discover/Comment/getReplies?comment_id=${comment.comment_id}`,
                    method: 'GET'
                });
                console.log("获取回复新增loadMoreReplies方法", res)
                if (res.code === 1) {
                    const replies = res.data.replies || [];

                    // 格式化回复内容
                    const formattedReplies = replies.map(reply => {
                        // 应用与初始评论相同的格式化逻辑
                        if (!reply.content.startsWith('@')) {
                            reply.content = `${reply.reply_nickname} ：${reply.formatted_content}`;
                        }
                        return reply;
                    });

                    // 更新回复列表，追加新回复而不是替换
                    if (!comment.replies) {
                        this.$set(comment, 'replies', formattedReplies);
                    } else {
                        // 确保不会重复添加相同回复
                        const existingIds = new Set(comment.replies.map(r => r.reply_id));
                        const newReplies = formattedReplies.filter(r => !existingIds.has(r.reply_id));
                        const updatedReplies = [...comment.replies, ...newReplies];
                        this.$set(comment, 'replies', updatedReplies);
                    }
                } else {
                    uni.showToast({ title: res.data.msg, icon: 'none' });
                }
            } catch (error) {
                uni.showToast({ title: '加载回复失败', icon: 'none' });
            }
        },

        // 修改likeComment方法
        async likeComment(comment, cIndex, dIndex) {
            // 检查用户是否已登录
            const token = uni.getStorageSync('token');
            if (!token) {
                uni.showToast({ title: '请先登录', icon: 'none' });
                uni.navigateTo({ url: '/pages/pageLogin/index' });

                return;
            }

            // 检查必要参数
            if (!comment.comment_id || comment.isLikedDisabled) return;

            // 禁用点赞按钮防止重复点击
            this.$set(comment, 'isLikedDisabled', true);

            // 保存原始状态用于回滚
            const originalLiked = comment.liked;
            const originalLikes = comment.likes;

            // 乐观更新UI（立即改变前端状态）
            this.$set(comment, 'liked', !originalLiked);
            this.$set(comment, 'likes', originalLiked ? originalLikes - 1 : originalLikes + 1);

            // 强制UI更新
            this.$forceUpdate();

            try {
                const res = await request({
                    url: 'discover/Like/toggle',
                    method: 'POST',
                    data: {
                        comment_id: comment.comment_id,
                        type: 'comment'  // 明确指定类型为评论点赞
                    }
                });

                if (res.code === 1) {
                    // 根据后端返回的action确认状态
                    const isLiked = res.data.action === 'like';

                    // 如果前端和后端状态不一致，则修正
                    if (comment.liked !== isLiked) {
                        this.$set(comment, 'liked', isLiked);
                        this.$set(comment, 'likes', isLiked ? originalLikes + 1 : originalLikes - 1);
                    }
                } else {
                    // 请求失败回滚状态
                    this.$set(comment, 'liked', originalLiked);
                    this.$set(comment, 'likes', originalLikes);
                    uni.showToast({ title: res.msg, icon: 'none' });
                }
            } catch (error) {
                // 网络错误回滚状态
                this.$set(comment, 'liked', originalLiked);
                this.$set(comment, 'likes', originalLikes);
                uni.showToast({ title: '操作失败', icon: 'none' });
            } finally {
                // 重新启用点赞按钮
                this.$set(comment, 'isLikedDisabled', false);
            }
        },


        onShare(item) {
            console.log('点击自定义分享按钮', wx);

            if (typeof wx === 'undefined') {
                console.error('wx 对象未定义，可能不在微信小程序环境');
                return;
            }
            // 存储当前要分享的动态数据
            this.currentShareItem = item;
            // 临时设置needCheckContentLength为false，防止分享时触发检查
            const originalNeedCheck = this.needCheckContentLength;
            this.needCheckContentLength = false;

            // 显示微信原生分享菜单
            wx.showShareMenu({
                withShareTicket: true,
                menus: ['shareAppMessage', 'shareTimeline']
            });

            // 2秒后恢复原状态
            setTimeout(() => {
                this.needCheckContentLength = originalNeedCheck;
            }, 2000);
        },



       // 分享给朋友
        onShareAppMessage() {
            // if (this.currentShareItem) {
            //     let title = this.currentShareItem.content
            //         ? this.currentShareItem.content.substring(0, 30) + '...'
            //         : '来自Online Didi的分享';
            //     let imageUrl = '/static/image/logo.jpg';
            //     if (this.currentShareItem.media && this.currentShareItem.media.length > 0 && this.currentShareItem.media[0].type === 'image') {
            //         imageUrl = getFullImageUrl(this.currentShareItem.media[0].url);
            //     }
            //     return {
            //         title: title,
            //         path: `/pages/discover/index?id=${this.currentShareItem.post_id || ''}`,
            //         imageUrl: imageUrl
            //     };
            // }
            return {
                title: '发现有趣的动态内容，快来看看吧！',
                path: '/pages/discover/index',
                imageUrl: this.getFullImageUrl('/index/logo.jpg')
            };
        },

        // 分享到朋友圈
        onShareTimeline() {
            if (this.currentShareItem) {
                let title = this.currentShareItem.content
                    ? this.currentShareItem.content.substring(0, 30) + '...'
                    : '来自Online Didi的分享';
                let imageUrl = '/static/image/logo.jpg';
                if (this.currentShareItem.media && this.currentShareItem.media.length > 0 && this.currentShareItem.media[0].type === 'image') {
                    imageUrl = getFullImageUrl(this.currentShareItem.media[0].url);
                }
                return {
                    title: title,
                    query: `from=timeline&id=${this.currentShareItem.post_id || ''}`,
                    imageUrl: imageUrl
                };
            }
            return {
                title: '有有趣的动态内容，一起来分享吧！',
                query: 'from=timeline',
                imageUrl: this.getFullImageUrl('/index/logo.jpg')
            };
        },



        // 处理分享错误
        handleShareError(platform, err) {
            console.error(`分享到${platform}失败:`, err);
            // 根据错误类型显示更具体的提示
            if (err.errMsg && err.errMsg.includes('not supported')) {
                // 特殊处理'method not supported'错误，提供手动分享选项
                this.showManualShareTip(platform);
            } else {
                let errorMsg = `分享到${platform}失败`;
                if (err.errMsg && err.errMsg.includes('cancel')) {
                    errorMsg = '分享已取消';
                }
                uni.showToast({
                    title: errorMsg,
                    icon: 'none'
                });
            }
        },

        // 显示手动分享提示
        showManualShareTip(platform) {
            uni.showModal({
                title: '分享提示',
                content: `当前环境暂不支持自动分享到${platform}。\n\n请尝试使用系统自带的分享功能或截图分享。`,
                showCancel: false,
                confirmText: '知道了'
            });
        },

        // 使用系统分享
        useSystemShare(title, imageUrl, platform) {
            // 不调用uni.share，而是显示一个提示，说明当前环境不支持自动分享
            // 这是因为在某些环境下，uni.share可能会失败
            uni.showModal({
                title: '分享',
                content: `当前环境不支持自动分享到${platform}。\n您可以手动复制以下内容进行分享：\n\n标题：${title}`,
                showCancel: false,
                confirmText: '知道了'
            });
        },
        // 图片预览
        openImageViewer(item, mediaIndex) {
            // 找到对应索引的图片
            const targetMedia = item.media[mediaIndex];
            if (targetMedia && targetMedia.type === 'image') {
                this.viewerData = {
                    avatar: item.avatar,
                    nickname: item.nickname,
                    imageUrl: targetMedia.url,
                    content: item.content,
                    likeCount: item.likes,
                    commentCount: item.comments.length,
                    liked: item.liked
                };
                this.showImageViewer = true;
            }
        },
        handleImageLike() {
            // 找到当前查看的动态项
            const currentItem = this.dynamicList.find(item =>
                item.media && item.media.some(media => 
                    media.type === 'image' && media.url === this.viewerData.imageUrl
                )
            );

            if (currentItem) {
                // 直接调用toggleLike方法，确保逻辑统一
                this.toggleLike(currentItem);
            }
        },
        handleImageComment() {
            // 直接在图片查看器内打开评论弹窗，不关闭图片弹窗
            const currentItem = this.dynamicList.find(item => 
                item.media && item.media.some(media => 
                    media.type === 'image' && media.url === this.viewerData.imageUrl
                )
            );
            if (currentItem) {
                const index = this.dynamicList.indexOf(currentItem);
                this.openCommentModal(currentItem, index);
            }
        },

        // 评论展开收起
        // 修改toggleContentExpand方法
        toggleContentExpand(item, index) {
            this.$set(item, 'isExpanded', !item.isExpanded);
            if (!item.isExpanded) {
                this.$nextTick(() => {
                    setTimeout(() => {
                        this.checkSingleContentHeight(item, index);
                    }, 300);
                });
            }
        },

        // 新增方法：检查单个动态内容高度
        checkSingleContentHeight(item, index) {
            // 检查item和item.content是否存在
            if (!item || !item.content) {
                console.warn(`动态 ${item?.post_id} 的内容不存在`);
                return;
            }

            // 先根据内容长度做一个简单的预判断，降低阈值提高检出率
            if (item.content.length > 150) {
                // 对于较长的内容，直接设置shouldShowToggle为true
                this.$set(item, 'shouldShowToggle', true);
                console.log(`动态 ${item.post_id} 内容长度 ${item.content.length} > 150，直接显示展开按钮`);
                return;
            }

            this.$nextTick(() => {
                try {
                    // 尝试使用多种方式查询元素
                    const elementId = `content_${index}`;
                    const query = uni.createSelectorQuery().in(this);

                    // 先尝试通过ID查询
                    query.select(`#${elementId}`).boundingClientRect().exec((res) => {
                        if (res && res[0]) {
                            const maxHeight = 138; // 3行高度(rpx)
                            const shouldShow = res[0].height > maxHeight;
                            this.$set(item, 'shouldShowToggle', shouldShow);
                            // console.log(`动态 ${item.post_id} 内容高度: ${res[0].height}, 显示展开按钮: ${shouldShow}`);
                        } else {
                            // 如果通过ID查询失败，尝试使用ref查询
                            console.warn(`未获取到动态 ${item.post_id} 的内容高度，通过ID查询失败`);
                            // 使用后备判断，进一步降低阈值
                            if (item.content.length > 80) {
                                this.$set(item, 'shouldShowToggle', true);
                                // console.log(`动态 ${item.post_id} 内容长度 ${item.content.length} > 80，后备判断显示展开按钮`);
                            }
                        }
                    });
                } catch (error) {
                    console.error(`检查动态 ${item.post_id} 内容高度时出错:`, error);
                    // 出错时的后备判断，使用更低的阈值
                    if (item.content.length > 80) {
                        this.$set(item, 'shouldShowToggle', true);
                        console.log(`动态 ${item.post_id} 检查出错，内容长度 ${item.content.length} > 80，强制显示展开按钮`);
                    }
                }
            });
        },

        // 增强checkContentLength方法，完善重试机制
        checkContentLength() {
            console.log('开始检查动态内容长度');

            // 初次检查
            this.$nextTick(() => {
                setTimeout(() => {
                    if (this.dynamicList && this.dynamicList.length > 0) {
                        console.log(`初次检查 ${this.dynamicList.length} 条动态内容`);
                        this.dynamicList.forEach((item, index) => {
                            this.checkSingleContentHeight(item, index);
                        });
                    }
                }, 300);
            });

            // 增强的重试机制，使用更多重试次数和递增延迟
            const checkWithRetry = (retryCount = 0) => {
                // 根据重试次数递增延迟时间
                const delay = 300 + (retryCount * 200);

                setTimeout(() => {
                    if (this.dynamicList && this.dynamicList.length > 0) {
                        // console.log(`第${retryCount + 1}次重试检查动态内容`);
                        this.$nextTick(() => {
                            this.dynamicList.forEach((item, index) => {
                                // 重试检查更广泛的内容范围，降低阈值提高检出率
                                if ((!item.shouldShowToggle && item.content && item.content.length > 80) ||
                                    (item.shouldShowToggle && item.isExpanded && !item.contentExpandedChecked)) {
                                    console.log(`重试检查动态 ${item.post_id} 的内容高度`);
                                    this.checkSingleContentHeight(item, index);
                                }
                            });
                        });
                    }
                }, delay);

                // 增加重试次数到5次，确保所有内容都有足够的检查机会
                if (retryCount < 4) {
                    setTimeout(() => checkWithRetry(retryCount + 1), delay + 300);
                }
            };

            // 启动重试检查
            setTimeout(() => checkWithRetry(), 500);
        },

        // 动态点赞功能
        async toggleLike(item) {
            // 检查用户是否已登录
            const token = uni.getStorageSync('token');
            if (!token) {
                uni.showToast({ title: '请先登录', icon: 'none' });
                uni.navigateTo({ url: '/pages/pageLogin/index' });

                return;
            }

            // 禁用点赞按钮防止重复点击
            this.$set(item, 'isLikedDisabled', true);

            // 保存原始状态用于回滚
            const originalLiked = item.liked;
            const originalLikes = item.likes;

            // 乐观更新UI
            this.$set(item, 'liked', !originalLiked);
            this.$set(item, 'likes', originalLiked ? originalLikes - 1 : originalLikes + 1);

            // 同步图片查看器状态
            this.syncImageViewerLikeState(item);

            try {
                const res = await request({
                    url: 'discover/Like/toggle',
                    method: 'POST',
                    data: { post_id: item.post_id }
                });

                if (res.code === 1) {
                    // 根据后端返回的action确定最终状态
                    const isLiked = res.data.action === 'like';
                    // console.log('后端返回状态:', item.liked);
                    if (item.liked !== isLiked) {
                        this.$set(item, 'liked', isLiked);
                        this.$set(item, 'likes', isLiked ? item.likes + 1 : item.likes - 1);
                        this.syncImageViewerLikeState(item);
                    }
                } else {
                    // 请求失败回滚状态
                    this.rollbackLikeState(item, originalLiked, originalLikes);
                    uni.showToast({ title: res.data.msg || '操作失败', icon: 'none' });
                }
            } catch (error) {
                // 网络错误回滚状态
                this.rollbackLikeState(item, originalLiked, originalLikes);
                uni.showToast({ title: '网络请求失败', icon: 'none' });
            } finally {
                // 重新启用点赞按钮
                this.$set(item, 'isLikedDisabled', false);
            }
        },

        // 同步图片查看器的点赞状态
        syncImageViewerLikeState(item) {
            if (this.showImageViewer && item.media && item.media.some(media => 
                media.type === 'image' && media.url === this.viewerData.imageUrl
            )) {
                this.$set(this.viewerData, 'liked', item.liked);
                this.$set(this.viewerData, 'likeCount', item.likes);
            }
        },

        // 回滚点赞状态
        rollbackLikeState(item, originalLiked, originalLikes) {
            this.$set(item, 'liked', originalLiked);
            this.$set(item, 'likes', originalLikes);
            this.syncImageViewerLikeState(item);
        },

        // 获取动态列表
        getDynamicList(isLoadMore = false) {
            // 如果是加载更多且没有更多数据，则直接返回
            if (isLoadMore && !this.hasMoreData) {
                console.log('没有更多数据了');
                return Promise.resolve();
            }

            // 设置加载状态
            this.loading = true;
            console.log('getDynamicList: 开始加载数据，loading=' + this.loading + ', page=' + this.currentPage);

            return new Promise((resolve) => {
                request({
                    url: `discover/Post/getList?page=${this.currentPage}`,
                    success: (res) => {
                        if (res.data.code === 1) {
                            console.log("获取动态列表", res);
                            const newData = res.data.data.data.map(item => {
                                // 清理media_urls和media_types中的空格和引号
                                const cleanMediaUrls = item.media_urls ? item.media_urls.replace(/[`\s]/g, '') : '';
                                const cleanMediaTypes = item.media_types ? item.media_types.replace(/[`\s]/g, '') : '';

                                // 处理媒体数据
                                const media = cleanMediaUrls && cleanMediaTypes ? cleanMediaUrls.split(',').map((url, index) => ({
                                    url: url.trim(),
                                    type: cleanMediaTypes.split(',')[index]?.trim() || 'image'
                                })) : [];

                                // 兼容原有图片数组
                                const images = item.image_urls ?
                                    item.image_urls.split(',').map(url => url.trim()) :
                                    (cleanMediaUrls ?
                                        cleanMediaUrls.split(',').filter((_, index) =>
                                            cleanMediaTypes.split(',')[index]?.trim() === 'image'
                                        ).map(url => url.trim()) :
                                        []
                                    );

                                // 视频数组
                                const videos = cleanMediaUrls && cleanMediaTypes ?
                                    cleanMediaUrls.split(',').filter((_, index) =>
                                        cleanMediaTypes.split(',')[index]?.trim() === 'video'
                                    ).map(url => url.trim()) :
                                    [];

                                // console.log(`处理动态 ${item.post_id} 媒体数据:`, {
                                //     mediaUrls: cleanMediaUrls,
                                //     mediaTypes: cleanMediaTypes,
                                //     mediaCount: media.length,
                                //     imageCount: images.length,
                                //     videoCount: videos.length
                                // });

                                // 添加调试日志，打印后端返回的comment_count值
                                console.log('动态列表接口返回的comment_count:', {
                                    postId: item.post_id,
                                    commentCount: item.comment_count
                                });

                                return {
                                    ...item,
                                    media,
                                    images,
                                    videos,
                                    liked: Boolean(item.is_liked),
                                    likes: Number(item.like_count) || 0,
                                    isExpanded: false,
                                    shouldShowToggle: false,
                                    comments: [],
                                    isLikedDisabled: false,
                                    user_id: item.user_id,
                                };
                            });

                            // 处理数据加载逻辑
                            if (isLoadMore) {
                                // 加载更多：追加数据
                                if (newData.length > 0) {
                                    this.dynamicList = [...this.dynamicList, ...newData];
                                }

                                // 检查是否还有更多数据
                                if (this.currentPage >= res.data.data.last_page) {
                                    this.hasMoreData = false;
                                    console.log('getDynamicList: 已到达最后一页，hasMoreData=false');
                                }
                            } else {
                                // 首次加载或刷新：替换数据
                                this.dynamicList = newData;
                                this.hasMoreData = this.currentPage < res.data.data.last_page;
                                console.log('getDynamicList: 首次加载，总页数=' + res.data.data.last_page + ', hasMoreData=' + this.hasMoreData);
                            }

                            // 设置标志位，通知需要检查内容长度
                            this.needCheckContentLength = true;

                            // 重置加载状态
                            this.loading = false;
                            console.log('getDynamicList: 加载完成，loading=' + this.loading + ', 当前页=' + this.currentPage + ', 总页数=' + res.data.data.last_page);
                            resolve();
                        }
                    },
                    fail: () => {
                        this.loading = false;
                        console.log('getDynamicList: 加载失败，loading=' + this.loading);
                        resolve();
                    }
                });
            });
        },


        // 获取评论列表
        getComments(post_id, index, page = 1) {
            return new Promise((resolve) => {
                request({
                    url: `discover/Comment/getList?post_id=${post_id}&page=${page}`,
                    method: 'GET',
                    success: (res) => {
                        console.log("获取评论列表", res);
                        // 将 res.data.code 改为 res.code
                        if (res.data.code === 1) {
                            if (this.dynamicList && this.dynamicList[index]) {
                                const comments = Array.isArray(res.data.data.data) ? res.data.data.data : [];

                                // 添加调试日志，打印后端返回的原始数据
                                console.log('后端返回的原始评论数据:', JSON.parse(JSON.stringify(comments)));
                                // 处理评论数据
                                comments.forEach(comment => {
                                    comment.time = comment.comment_time;
                                    comment.liked = Boolean(comment.is_liked);
                                    comment.likes = Number(comment.like_count) || 0;
                                    // 保留user_id字段，用于回复评论时获取被回复用户ID
                                    comment.user_id = comment.user_id;
                                    // 添加 isExpanded 属性并初始化为 false
                                    comment.isExpanded = false;

                                    // 处理回复数据
                                    if (comment.replies && comment.replies.length > 0) {
                                        comment.replies.forEach(reply => {
                                            reply.isExpanded = false; // 确保回复也有 isExpanded 属性

                                            // 直接使用后端返回的formatted_content
                                            if (reply.formatted_content) {
                                                // 使用手机号格式化显示
                                                const displayPhone = reply.reply_phone ? reply.reply_phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2') : reply.reply_nickname;
                                                // 保留后端返回的'回复 @用户名: '格式
                                                reply.content = `${displayPhone}： ${reply.formatted_content}`;
                                            }
                                        });
                                    }
                                    else {
                                        comment.replies = []; // 确保 replies 存在
                                    }
                                });

                                if (page === 1) {
                                    this.$set(this.dynamicList[index], 'comments', comments);
                                } else {
                                    // 确保不会重复添加相同评论
                                    const existingIds = new Set(this.dynamicList[index].comments.map(c => c.comment_id));
                                    const newComments = comments.filter(c => !existingIds.has(c.comment_id));
                                    const updatedComments = [...this.dynamicList[index].comments, ...newComments];
                                    this.$set(this.dynamicList[index], 'comments', updatedComments);
                                }

                                // 存储分页信息
                                this.$set(this.dynamicList[index], 'pagination', {
                                    total: res.data.data.total,
                                    per_page: res.data.data.per_page,
                                    current_page: res.data.data.current_page,
                                    last_page: res.data.data.last_page
                                });

                                // 不再更新评论总数，统一使用Post/getList接口返回的comment_count
                                console.log('不再更新评论总数，使用Post/getList接口返回的comment_count:', {
                                    oldCount: this.dynamicList[index].comment_count,
                                    newCount: this.dynamicList[index].comment_count,
                                    postId: post_id
                                });
                            }
                        } else {
                            uni.showToast({ title: res.data.msg, icon: 'none' });
                        }
                        resolve();
                    },
                    fail: () => {
                        uni.showToast({ title: '获取评论列表失败', icon: 'none' });
                        resolve();
                    }
                });
            });
        },

        // 加载更多评论
        loadMoreComments(event, index) {
            const item = this.dynamicList[index];
            // 检查是否有分页信息，并且当前页小于最后一页
            if (item.pagination && item.pagination.current_page < item.pagination.last_page) {
                const nextPage = item.pagination.current_page + 1;
                this.getComments(item.post_id, index, nextPage);
            }
        },

        // 加载更多动态数据
        loadMoreData() {
            console.log('loadMoreData: 检查是否可以加载更多，loading=' + this.loading + ', hasMoreData=' + this.hasMoreData);
            // 如果正在加载中或没有更多数据，则不触发加载更多
            if (this.loading || !this.hasMoreData) {
                console.log('未触发加载更多，原因: loading=' + this.loading + ', hasMoreData=' + this.hasMoreData);
                return;
            }

            // 增加页码
            this.currentPage++;
            console.log('loadMoreData: 开始加载第' + this.currentPage + '页数据');
            // 调用获取动态列表方法，传入isLoadMore=true表示加载更多
            this.getDynamicList(true);
        },

        // 下拉刷新
        onPullDownRefresh() {
            console.log('onPullDownRefresh: 下拉刷新');
            // 重置页码
            this.currentPage = 1;
            // 重置有更多数据的状态
            this.hasMoreData = true;
            // 调用获取动态列表方法，传入isLoadMore=false表示刷新
            this.getDynamicList(false).then(() => {
                uni.stopPullDownRefresh();
                console.log('onPullDownRefresh: 刷新完成');
            });
        },

        // 滚动到底部触发加载更多
        onReachBottom() {
            console.log('onReachBottom: 滚动到底部');
            // 调用加载更多数据方法
            this.loadMoreData();
        },



    },

    // 在created生命周期中获取用户信息
    created() {
        this.fetchUserInfo();
    },

    mounted() {
        console.log('mounted: 页面挂载，首次加载数据');
        this.currentPage = 1;
        this.hasMoreData = true;
        this.getDynamicList(false);
        this.$nextTick(() => {
            setTimeout(() => {
                this.checkContentLength();
                this.needCheckContentLength = true;
            }, 500);
        });
    },

    onShow() {
        console.log('onShow: 页面显示');
        // 检查是否从发布成功页面跳转过来
        const pages = getCurrentPages();
        const currentPage = pages[pages.length - 1];
        const options = currentPage.options || {};

        if (options.from === 'release_success') {
            // 检查是否已经显示过弹窗，避免重复触发
            const hasShownSuccess = uni.getStorageSync('release_success_shown');
            if (!hasShownSuccess) {
                // 延迟显示弹窗，确保页面完全加载
                setTimeout(() => {
                    this.showReleaseSuccessPopup = true;
                    setTimeout(() => {
                        this.showReleaseSuccessPopup = false;
                    }, 2000);
                }, 800);
                
                // 标记已显示过
                uni.setStorageSync('release_success_shown', true);
            }
        };
    },

    updated() {
        this.$nextTick(() => {
            // 修复分享按钮点击页面抖动问题：添加条件判断，避免在每次更新时都检查内容长度
            if (this.needCheckContentLength) {
                setTimeout(() => {
                    this.checkContentLength();
                    // 重置标记
                    this.needCheckContentLength = false;
                }, 500);
            }
        });
    }
}
</script>

<style lang="scss" src="./index.scss"></style>
